<template>
  <div class="shelf-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="选择仓库">
          <el-select
            v-model="searchForm.warehouseId"
            placeholder="请选择"
            filterable
            clearable
            style="width: 260px"
            :loading="warehouseLoading"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货架名称">
          <el-input
            v-model="searchForm.shelfName"
            placeholder="请输入货架名称"
            clearable
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="table-card">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="openDialog">添加</el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="shelfId"
        style="width: 100%"
        v-loading="loading"
        height="350px"
      >
        <el-table-column fixed="left" type="index" label="序号" width="60" />
        <el-table-column prop="shelfName" label="货架名称" width="150" />
        <el-table-column prop="shelfCode" label="货架编码" width="120" />
        <el-table-column prop="warehouseName" label="所属库房" width="200" />
        <el-table-column prop="shelfType" label="货架类型" width="120" />
        <el-table-column prop="shelfDepth" label="深度" width="120" />
        <el-table-column prop="shelfRow" label="货架号" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.shelfState === 1 ? 'success' : 'danger'">
              {{ row.shelfState === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.updateTime || row.createrTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" width="120">
          <template #default="{ row }">
            {{ row.updater || row.createor || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="{ row }">
            <el-button link size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button link size="small" type="info" @click="openDetailDialog(row)">查看</el-button>
            <el-button link size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <el-card class="action-card">
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pageinfo.pageIndex"
          v-model:page-size="pageinfo.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pageinfo.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑货架弹框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px" 
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货架名称" prop="shelfName">
              <el-input 
                v-model="form.shelfName" 
                placeholder="请输入货架名称" 
                clearable 
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货架编码" prop="shelfCode">
              <el-input 
                v-model="form.shelfCode" 
                placeholder="点击自动生成按钮获取编号" 
                readonly
                :disabled="isViewMode"
              >
                <template v-if="dialogMode === 'add'" #append>
                  <el-button @click="generateShelfCode" :loading="generatingCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="warehouseLoading"
                @change="handleWarehouseChange"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属库区" prop="storagelocationId">
              <el-select
                v-model="form.storagelocationId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="storagelocationLoading"
                :disabled="!form.warehouseId || isViewMode"
              >
                <el-option
                  v-for="item in storagelocationOptions"
                  :key="item.storagelocationId"
                  :label="item.storagelocationName"
                  :value="item.storagelocationId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属巷道" prop="driftId">
              <el-select
                v-model="form.driftId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="driftLoading"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in driftOptions"
                  :key="item.driftId"
                  :label="item.driftName"
                  :value="item.driftId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排号" prop="shelfRow">
              <el-input 
                v-model="form.shelfRow" 
                placeholder="请输入排号" 
                clearable 
                type="number"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="深度" prop="shelfDepthId">
              <el-select
                v-model="form.shelfDepthId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :loading="depthLoading"
                :disabled="isViewMode"
              >
                <el-option
                  v-for="item in depthOptions"
                  :key="item.dictionaryId"
                  :label="item.dictionaryName"
                  :value="item.dictionaryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货架类型" prop="shelfTypeId">
              <el-radio-group v-model="form.shelfTypeId" :disabled="isViewMode">
                <el-radio 
                  v-for="item in shelfTypeOptions" 
                  :key="item.dictionaryId" 
                  :value="item.dictionaryId"
                >
                  {{ item.dictionaryName }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="shelfState">
              <el-radio-group v-model="form.shelfState" :disabled="isViewMode">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="form.shelfDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
            :disabled="isViewMode"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ dialogMode === 'view' ? '关闭' : '取消' }}</el-button>
          <el-button 
            v-if="dialogMode !== 'view'"
            type="primary" 
            @click="handleSave" 
            :loading="saving"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/http/MyAxios'

// 查询条件
const searchForm = reactive({
  shelfName: '', // 货架名称（模糊查询）
  warehouseId: null as number | null, // 所属仓库（精确查询）
})

// 分页信息
const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 仓库选项
const warehouseOptions = ref<Array<{ warehouseId: number; warehouseName: string }>>([])
const warehouseLoading = ref(false)

// 弹框相关
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit' | 'view'>('add')
const currentShelfId = ref<number | null>(null)
const formRef = ref<FormInstance>()
const saving = ref(false)
const dialogTitle = computed(() => {
  if (dialogMode.value === 'edit') return '编辑货架'
  if (dialogMode.value === 'view') return '查看货架'
  return '添加货架'
})
const isViewMode = computed(() => dialogMode.value === 'view')

// 表单数据
const form = reactive({
  shelfId: null as number | null,
  shelfName: '',
  shelfCode: '',
  warehouseId: null as number | null,
  storagelocationId: null as number | null,
  driftId: null as number | null,
  shelfRow: null as number | null,
  shelfDepthId: null as number | null,
  shelfTypeId: null as number | null,
  shelfState: 1, // 默认启用
  shelfDesc: '',
})

// 表单验证规则
const rules: FormRules = {
  shelfName: [{ required: true, message: '请输入货架名称', trigger: 'blur' }],
  shelfCode: [{ required: true, message: '请输入货架编码', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请选择所属库房', trigger: 'change' }],
  storagelocationId: [{ required: true, message: '请选择所属库区', trigger: 'change' }],
  driftId: [{ required: true, message: '请选择所属巷道', trigger: 'change' }],
  shelfRow: [{ required: true, message: '请输入排号', trigger: 'blur' }],
  shelfDepthId: [{ required: true, message: '请选择深度', trigger: 'change' }],
  shelfTypeId: [{ required: true, message: '请选择货架类型', trigger: 'change' }],
  shelfState: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 库区选项
const storagelocationOptions = ref<Array<{ storagelocationId: number; storagelocationName: string }>>([])
const storagelocationLoading = ref(false)

// 巷道选项
const driftOptions = ref<Array<{ driftId: number; driftName: string }>>([])
const driftLoading = ref(false)

// 深度选项（字典）
const depthOptions = ref<Array<{ dictionaryId: number; dictionaryName: string }>>([])
const depthLoading = ref(false)

// 货架类型选项（字典）
const shelfTypeOptions = ref<Array<{ dictionaryId: number; dictionaryName: string }>>([])
const shelfTypeLoading = ref(false)

// 编号生成相关
const generatingCode = ref(false)

const formatDate = (val?: string | Date | null) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD')
}

// 加载仓库列表（复用GetPlatformView页面的逻辑）
const loadWarehouses = async () => {
  if (warehouseLoading.value) return
  warehouseLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehousing/GetWarehouse',
      method: 'get',
    })
    if (res.data?.code === 200 || res.data?.success) {
      const warehouses = res.data.data || []
      warehouseOptions.value = warehouses.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseName: item.warehouseName,
      }))
    } else {
      ElMessage.error(res.data?.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败，请稍后重试')
  } finally {
    warehouseLoading.value = false
  }
}

// 获取货架列表（分页）
const getShelfList = () => {
  loading.value = true
  myaxios({
    url: '/api/Shelf/GetShelfPage',
    method: 'get',
    params: {
      Pageindex: pageinfo.pageIndex,
      PageSize: pageinfo.pageSize,
      shelfName: searchForm.shelfName || undefined,
      warehouseId: searchForm.warehouseId || undefined,
    },
  })
    .then(res => {
      const data = res.data?.data
      // 后端分页结构：data.data 为列表，data.listCount 为总数
      tableData.value = data?.data || []
      pageinfo.total = data?.listCount || 0
    })
    .catch(err => {
      console.error('获取货架列表失败:', err)
      ElMessage.error('获取货架列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询
const handleSearch = () => {
  pageinfo.pageIndex = 1
  getShelfList()
}

// 重置
const handleReset = () => {
  searchForm.shelfName = ''
  searchForm.warehouseId = null
  pageinfo.pageIndex = 1
  getShelfList()
}

// 分页尺寸变化
const handleSizeChange = (val: number) => {
  pageinfo.pageSize = val
  pageinfo.pageIndex = 1
  getShelfList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  pageinfo.pageIndex = val
  getShelfList()
}

// 判断是否为根字典（父级id为0或null）
const isRootDictionary = (item: any) => {
  return !item?.dictionaryParentId || item.dictionaryParentId === 0 || item.dictionaryParentId === '0' || item.dictionaryParentId === null
}

// 匹配字典项
const matchDictionary = (item: any, names: string[], codes: string[]) => {
  const name = (item?.dictionaryName || '').toLowerCase()
  const code = (item?.dictionaryCode || '').toLowerCase()
  return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
    codes.some(c => code === c.toLowerCase())
}

// 查找父级字典ID
const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
  const params = { Pageindex: 1, PageSize: 1000 }
  try {
    const res = await myaxios.get('/api/Dictionary/GetDictionaryList', { params })
    const list = res.data?.data?.data || []
    const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
    if (found?.dictionaryId) return found.dictionaryId
  } catch (error) {
    console.warn('获取字典列表失败', error)
  }

  for (const name of nameCandidates) {
    try {
      const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
        params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
      })
      const list = res.data?.data?.data || []
      const found = list.find((item: any) => isRootDictionary(item))
      if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
      console.warn(`按名称 ${name} 获取字典失败`, error)
    }
  }
  return null
}

// 获取字典子项
const fetchDictionaryChildren = async (parentId: string | number | null) => {
  if (!parentId) return []
  try {
    const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
      params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
    })
    return res.data?.data?.data || []
  } catch (error) {
    console.warn('获取字典子项失败', error)
    return []
  }
}

// 加载深度列表
const loadDepthList = async () => {
  if (depthLoading.value) return
  depthLoading.value = true
  try {
    const parentId = await findDictionaryParentId(['货架深度'], ['shelfdepth', 'shelf_depth'])
    if (!parentId) {
      ElMessage.warning('未找到货架深度字典，请先配置字典')
      return
    }
    const children = await fetchDictionaryChildren(parentId)
    depthOptions.value = children.map((item: any) => ({
      dictionaryId: item.dictionaryId,
      dictionaryName: item.dictionaryName
    }))
  } catch (error) {
    console.error('加载深度列表失败:', error)
    ElMessage.error('加载深度列表失败，请稍后重试')
  } finally {
    depthLoading.value = false
  }
}

// 加载货架类型列表
const loadShelfTypeList = async () => {
  if (shelfTypeLoading.value) return
  shelfTypeLoading.value = true
  try {
    const parentId = await findDictionaryParentId(['货架类型'], ['shelftype', 'shelf_type'])
    if (!parentId) {
      ElMessage.warning('未找到货架类型字典，请先配置字典')
      return
    }
    const children = await fetchDictionaryChildren(parentId)
    shelfTypeOptions.value = children.map((item: any) => ({
      dictionaryId: item.dictionaryId,
      dictionaryName: item.dictionaryName
    }))
  } catch (error) {
    console.error('加载货架类型列表失败:', error)
    ElMessage.error('加载货架类型列表失败，请稍后重试')
  } finally {
    shelfTypeLoading.value = false
  }
}

const ensureBaseDataLoaded = async () => {
  await Promise.all([
    loadWarehouses(),
    loadDrifts(),
    loadDepthList(),
    loadShelfTypeList(),
  ])
}

// 加载库区列表（根据仓库ID）
const loadStoragelocations = async (warehouseId: number) => {
  if (!warehouseId) {
    storagelocationOptions.value = []
    return
  }
  if (storagelocationLoading.value) return
  storagelocationLoading.value = true
  try {
    const res = await myaxios.get('/api/Warehouse/GetStoragelocation', {
      params: {
        warehouseId: warehouseId,
        pageindex: 1,
        pagesize: 1000
      }
    })
    if (res.data?.code === 200 && res.data?.data?.data) {
      storagelocationOptions.value = res.data.data.data.map((item: any) => ({
        storagelocationId: item.storagelocationId,
        storagelocationName: item.storagelocationName
      }))
    } else {
      storagelocationOptions.value = []
    }
  } catch (error) {
    console.error('获取库区列表失败:', error)
    ElMessage.error('获取库区列表失败，请稍后重试')
    storagelocationOptions.value = []
  } finally {
    storagelocationLoading.value = false
  }
}

// 加载巷道列表
const loadDrifts = async () => {
  if (driftLoading.value) return
  driftLoading.value = true
  try {
    const res = await myaxios.get('/api/Drift/GetDriftPage', {
      params: {
        Pageindex: 1,
        PageSize: 1000
      }
    })
    if (res.data?.code === 200 && res.data?.data?.data) {
      driftOptions.value = res.data.data.data.map((item: any) => ({
        driftId: item.driftId,
        driftName: item.driftName
      }))
    } else {
      driftOptions.value = []
    }
  } catch (error) {
    console.error('获取巷道列表失败:', error)
    ElMessage.error('获取巷道列表失败，请稍后重试')
    driftOptions.value = []
  } finally {
    driftLoading.value = false
  }
}

const fillFormWithData = async (data: any) => {
  form.shelfId = data?.shelfId ?? null
  form.shelfName = data?.shelfName || ''
  form.shelfCode = data?.shelfCode || ''
  form.warehouseId = data?.warehouseId ?? null

  if (form.warehouseId) {
    await loadStoragelocations(form.warehouseId)
  } else {
    storagelocationOptions.value = []
  }

  form.storagelocationId = data?.storagelocationId ?? null
  form.driftId = data?.driftId ?? null
  form.shelfRow = data?.shelfRow ?? null
  form.shelfDepthId = data?.shelfDepthId ?? null
  form.shelfTypeId = data?.shelfTypeId ?? null
  form.shelfState = typeof data?.shelfState === 'number' ? data.shelfState : Number(data?.shelfState) || 1
  form.shelfDesc = data?.shelfDesc || ''
  formRef.value?.clearValidate()
}

const loadShelfDetail = async (shelfId: number) => {
  try {
    const res = await myaxios({
      url: '/api/Shelf/GetShelfDetail',
      method: 'get',
      params: { shelfId },
    })
    if (res.data?.code === 200 && res.data?.data) {
      await fillFormWithData(res.data.data)
      return true
    }
    ElMessage.error(res.data?.message || '获取货架详情失败')
    return false
  } catch (error) {
    console.error('获取货架详情失败:', error)
    ElMessage.error('获取货架详情失败，请稍后重试')
    return false
  }
}

// 仓库变化时加载库区
const handleWarehouseChange = (warehouseId: number | null) => {
  form.storagelocationId = null
  if (warehouseId) {
    loadStoragelocations(warehouseId)
  } else {
    storagelocationOptions.value = []
  }
}

// 重置表单
const resetForm = () => {
  form.shelfId = null
  form.shelfName = ''
  form.shelfCode = ''
  form.warehouseId = null
  form.storagelocationId = null
  form.driftId = null
  form.shelfRow = null
  form.shelfDepthId = null
  form.shelfTypeId = null
  form.shelfState = 1
  form.shelfDesc = ''
  currentShelfId.value = null
  formRef.value?.clearValidate()
}

// 打开新增弹框
const openDialog = async () => {
  dialogMode.value = 'add'
  resetForm()
  storagelocationOptions.value = []
  await ensureBaseDataLoaded()
  dialogVisible.value = true
}

// 编号生成相关函数
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestShelfCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: 'Shelf', targetName: '货架' }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn('[shelf] GenerateNumber 接口不可用，尝试规则生成', err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode: 'Shelf', targetName: '货架' }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateShelfCode = async () => {
  generatingCode.value = true
  try {
    form.shelfCode = await requestShelfCode()
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

// 保存货架
const handleSave = async () => {
  if (dialogMode.value === 'view') {
    dialogVisible.value = false
    return
  }
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 新增模式下，如果用户没有输入货架编码，自动生成
  if (dialogMode.value === 'add' && !form.shelfCode) {
    try {
      await generateShelfCode()
      if (!form.shelfCode) {
        ElMessage.warning('请先生成货架编码')
        return
      }
    } catch (error) {
      ElMessage.warning('生成货架编码失败，请稍后重试')
      return
    }
  }

  saving.value = true
  try {
    const data = {
      shelfName: form.shelfName,
      shelfCode: form.shelfCode,
      warehouseId: form.warehouseId,
      storagelocationId: form.storagelocationId,
      driftId: form.driftId,
      shelfRow: form.shelfRow,
      shelfDepthId: form.shelfDepthId,
      shelfTypeId: form.shelfTypeId,
      shelfState: form.shelfState,
      shelfDesc: form.shelfDesc || '',
    }

    let res
    if (dialogMode.value === 'add') {
      res = await myaxios({
        url: '/api/Shelf/CreateShelf',
        method: 'post',
        data,
      })
    } else {
      if (!currentShelfId.value) {
        ElMessage.error('缺少货架ID，无法保存')
        return
      }
      res = await myaxios({
        url: `/api/Shelf/UpdateShelf?shelfId=${currentShelfId.value}`,
        method: 'put',
        data,
      })
    }

    if (res.data?.code === 200) {
      ElMessage.success(res.data?.message || (dialogMode.value === 'add' ? '添加货架成功' : '更新货架成功'))
      dialogVisible.value = false
      getShelfList()
    } else {
      ElMessage.error(res.data?.message || (dialogMode.value === 'add' ? '添加货架失败' : '更新货架失败'))
    }
  } catch (error: any) {
    console.error(`${dialogMode.value === 'add' ? '添加' : '更新'}货架失败:`, error)
    const errorMsg =
      error?.response?.data?.message ||
      error?.message ||
      `${dialogMode.value === 'add' ? '添加' : '更新'}货架失败，请稍后重试`
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

const openShelfDialog = async (mode: 'edit' | 'view', row: any) => {
  const shelfId = row?.shelfId
  if (!shelfId) {
    ElMessage.warning('未找到货架ID')
    return
  }

  dialogMode.value = mode
  resetForm()
  currentShelfId.value = Number(shelfId)

  await ensureBaseDataLoaded()

  const success = await loadShelfDetail(Number(shelfId))
  if (success) {
    dialogVisible.value = true
  } else {
    dialogMode.value = 'add'
    currentShelfId.value = null
  }
}

// 打开编辑弹框
const openEditDialog = (row: any) => {
  openShelfDialog('edit', row)
}

// 打开详情弹框
const openDetailDialog = (row: any) => {
  openShelfDialog('view', row)
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确认删除这条货架信息吗？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      myaxios({
        url: '/api/Shelf/DeleteShelf',
        method: 'delete',
        params: { shelfId: row.shelfId },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '删除成功')
            getShelfList()
          } else {
            ElMessage.error(res.data?.message || '删除失败')
          }
        })
        .catch(error => {
          console.error('删除货架失败:', error)
          ElMessage.error('删除货架失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

onMounted(() => {
  loadWarehouses()
  getShelfList()
})
</script>

<style scoped>
.shelf-page {
  padding: 10px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 15px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>

